from . import admins_bp
from .forms.picture import EditForm
from ...extends import storage
from ...models import Picture, db
from flask import request, render_template, jsonify, flash, current_app
import requests


@admins_bp.route('/picture/upload', methods=['GET', 'POST'])
def picture_upload():
    if request.method == 'POST':
        upload = request.files.get('upload')
        src = request.form.get('src')
        if upload:
            f = request.files['upload']
        elif src:
            f = requests.get(src)
            if f.status_code != 200:
                return '', f.status_code
        else:
            return '', 400
        if f.headers['Content-Type'].split('/')[-1] not in current_app.config.get('STORAGE_EXTENSION_ALLOWED'):
            return '上传的图片不被允许', 400
        result = storage.save(f)
        with db .auto_commit():
            pic = Picture()
            pic.flag = result.flag
            pic.title = ''
            pic.src = result.url
            db.session.add(pic)
        return jsonify({
            'url': pic.url
        })
    return 'upload view'


@admins_bp.route('/picture/select')
def picture_select():
    record = Picture.query.order_by(Picture.id.desc()).paginate(per_page=21)
    return render_template('picture_select.html', record=record, page_title='图片管理')


@admins_bp.route('/picture/<int:picture_id>', methods=['GET', 'POST'])
def picture_modify(picture_id):
    pic = Picture.query.get_or_404(picture_id)
    ut = pic.update_time
    form = EditForm()
    if form.validate_on_submit():
        if form.file.data:
            storage.save(form.file.data, pic.flag.split('/')[-1])
        with db.auto_commit():
            pic.title = form.title.data or form.file.data.filename
        if ut != pic.update_time or form.file.data:
            flash('操作成功', 'success')
    form.title.data = pic.title
    form.flag.data = pic.flag
    form.src.data = pic.url
    form.create_datetime.data = pic.create_datetime
    form.update_datetime.data = pic.update_datetime
    return render_template('picture_edit.html', picture=pic, form=form)
